using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PDFHelper.Helper
{
    public class PdfPageEvent : PdfPageEventHelper
    {
        readonly IWaterMark _watermark;
        readonly IPageHeaderAndFooter _pageHeaderAndFooter;
        public PdfPageEvent(IPageHeaderAndFooter pageHeaderAndFooter, IWaterMark waterMark)
        {
            _watermark = waterMark;
            _pageHeaderAndFooter = pageHeaderAndFooter;
        }


        private void WriteWaterMark(PdfContentByte under, float pageHeight)
        {
            if (_watermark == null)
            {
                return;
            }

            switch (_watermark.WaterMarkType)
            {
                case WaterMarkType.Text:
                    const float xPosition = 300;
                    float yPosition = 200;
                    const float angle = 45;
                    Font font = _watermark.GetStringWaterMarkFont();

                    under.BeginText();
                    under.SetColorFill(BaseColor.LIGHT_GRAY);
                    under.SetFontAndSize(font.BaseFont, font.Size);
                    while (pageHeight > yPosition + 100)
                    {
                        under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _watermark.StringWaterMark, xPosition, yPosition, angle);

                        yPosition += 100;
                    }

                    under.EndText();
                    break;
                case WaterMarkType.Image:
                    under.AddImage(_watermark.GetImageWaterMark());
                    break;
                default:
                    break;
            }
        }

        public override void OnStartPage(PdfWriter writer, Document doc)
        {
            WriteWaterMark(writer.DirectContentUnder, doc.PageSize.Height);

            if (_pageHeaderAndFooter == null)
            {
                return;
            }

            PdfPTable table = _pageHeaderAndFooter.GetHeaderTable(doc.PageNumber, doc.PageSize.Width);
            if (table != null)
            {
                table.WriteSelectedRows(0, -1, 0, (doc.PageSize.Height - 10), writer.DirectContent);
            }
        }

        public override void OnEndPage(PdfWriter writer, Document doc)
        {
            if (_pageHeaderAndFooter == null)
            {
                return;
            }

            PdfPTable table = _pageHeaderAndFooter.GetFooterTable(doc.PageNumber, doc.PageSize.Width);
            if (table != null)
            {
                table.WriteSelectedRows(0, -1, 0, (doc.BottomMargin + 10), writer.DirectContent);
            }
        }
    }
}